# -*- coding: utf-8 -*-
import os
import tkinter as tk
from tkinter import filedialog, messagebox
import threading
from docx import Document
from reportlab.lib.pagesizes import letter
from reportlab.pdfgen import canvas
from reportlab.lib import colors
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle, Image
from io import BytesIO
from PIL import Image as PILImage
import sys

class WordToPdfConverterAlt:
    def __init__(self, root):
        self.root = root
        self.root.title("Word 转 PDF 转换器 (无需 MS Word)")
        self.root.geometry("500x250")
        self.root.resizable(False, False)
        
        # 配置样式
        self.root.configure(bg="#f5f5f5")
        
        # 标题标签
        self.header_label = tk.Label(
            root, 
            text="Word 批量转 PDF 工具", 
            font=("Arial", 16, "bold"), 
            bg="#f5f5f5"
        )
        self.header_label.pack(pady=20)
        
        # 选择文件夹按钮
        self.select_button = tk.Button(
            root, 
            text="选择包含Word文档的文件夹", 
            command=self.select_folder,
            font=("Arial", 10),
            bg="#4CAF50",
            fg="white",
            padx=10,
            pady=5
        )
        self.select_button.pack(pady=10)
        
        # 已选择文件夹路径标签
        self.folder_path_var = tk.StringVar()
        self.folder_path_var.set("未选择文件夹")
        self.folder_path_label = tk.Label(
            root, 
            textvariable=self.folder_path_var,
            font=("Arial", 9),
            bg="#f5f5f5",
            wraplength=450
        )
        self.folder_path_label.pack(pady=5)
        
        # 状态标签
        self.status_var = tk.StringVar()
        self.status_var.set("就绪 (无需 MS Word)")
        self.status_label = tk.Label(
            root, 
            textvariable=self.status_var,
            font=("Arial", 9, "italic"),
            bg="#f5f5f5"
        )
        self.status_label.pack(pady=5)
        
        # 转换按钮
        self.convert_button = tk.Button(
            root, 
            text="将所有Word文件转换为PDF", 
            command=self.start_conversion,
            font=("Arial", 10),
            bg="#2196F3",
            fg="white",
            padx=10,
            pady=5,
            state=tk.DISABLED
        )
        self.convert_button.pack(pady=10)
        
    def select_folder(self):
        folder_path = filedialog.askdirectory(title="选择包含Word文档的文件夹")
        if folder_path:
            self.folder_path = folder_path
            self.folder_path_var.set(folder_path)
            self.convert_button.config(state=tk.NORMAL)
            self.status_var.set("已选择文件夹。准备转换。")
    
    def start_conversion(self):
        # 在单独的线程中启动转换，防止GUI卡顿
        threading.Thread(target=self.convert_files, daemon=True).start()
    
    def docx_to_pdf(self, docx_path, pdf_path):
        """不需要MS Word将Word文档转换为PDF"""
        # 加载Word文档
        doc = Document(docx_path)
        
        # 创建PDF文档
        pdf = SimpleDocTemplate(
            pdf_path,
            pagesize=letter,
            rightMargin=72,
            leftMargin=72,
            topMargin=72,
            bottomMargin=72
        )
        
        # 创建样式
        styles = getSampleStyleSheet()
        normal_style = styles['Normal']
        heading1_style = styles['Heading1']
        heading2_style = styles['Heading2']
        
        # 创建一个列表来保存PDF元素
        elements = []
        
        # 处理Word文档中的每个段落
        for para in doc.paragraphs:
            if para.style.name.startswith('Heading1'):
                elements.append(Paragraph(para.text, heading1_style))
            elif para.style.name.startswith('Heading2'):
                elements.append(Paragraph(para.text, heading2_style))
            else:
                elements.append(Paragraph(para.text, normal_style))
            
            # 在每个段落后添加一个小间距
            elements.append(Spacer(1, 6))
        
        # 处理表格(基本支持)
        for table in doc.tables:
            data = []
            for row in table.rows:
                row_data = []
                for cell in row.cells:
                    # 获取单元格中的文本
                    cell_text = ""
                    for paragraph in cell.paragraphs:
                        cell_text += paragraph.text + "\n"
                    row_data.append(cell_text.strip())
                data.append(row_data)
            
            # 创建PDF表格
            if data:
                pdf_table = Table(data)
                pdf_table.setStyle(TableStyle([
                    ('BACKGROUND', (0, 0), (-1, 0), colors.lightgrey),
                    ('TEXTCOLOR', (0, 0), (-1, 0), colors.black),
                    ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
                    ('FONTNAME', (0, 0), (-1, 0), 'Helvetica-Bold'),
                    ('FONTSIZE', (0, 0), (-1, 0), 12),
                    ('BOTTOMPADDING', (0, 0), (-1, 0), 12),
                    ('BACKGROUND', (0, 1), (-1, -1), colors.white),
                    ('GRID', (0, 0), (-1, -1), 1, colors.black),
                ]))
                elements.append(pdf_table)
                elements.append(Spacer(1, 12))
        
        # 构建PDF
        pdf.build(elements)
    
    def convert_files(self):
        try:
            self.status_var.set("正在转换文件...")
            self.convert_button.config(state=tk.DISABLED)
            self.select_button.config(state=tk.DISABLED)
            
            # 获取文件夹中的Word文件列表
            word_files = []
            for file in os.listdir(self.folder_path):
                if file.endswith(".docx"):  # 此版本不支持.doc
                    word_files.append(os.path.join(self.folder_path, file))
            
            if not word_files:
                messagebox.showinfo("提示", "在选定的文件夹中未找到.docx文档。")
                self.status_var.set("未找到.docx文档。注意：不支持.doc文件。")
                self.convert_button.config(state=tk.NORMAL)
                self.select_button.config(state=tk.NORMAL)
                return
            
            # 成功转换的计数
            success_count = 0
            
            # 转换每个文件
            for i, word_file in enumerate(word_files):
                try:
                    base_name = os.path.splitext(word_file)[0]
                    pdf_file = "{0}.pdf".format(base_name)
                    
                    self.status_var.set("正在转换 {0}/{1}: {2}".format(i+1, len(word_files), os.path.basename(word_file)))
                    self.root.update()
                    
                    # 转换文件
                    self.docx_to_pdf(word_file, pdf_file)
                    success_count += 1
                    
                except Exception as e:
                    print("转换 {0} 时出错: {1}".format(word_file, e))
            
            self.status_var.set("转换完成！已转换 {0}/{1} 个文件。".format(success_count, len(word_files)))
            messagebox.showinfo("成功", "成功将 {0} 个（共 {1} 个）Word文档转换为PDF。".format(success_count, len(word_files)))
            
        except Exception as e:
            self.status_var.set("错误: {0}".format(str(e)))
            messagebox.showerror("错误", "发生错误: {0}".format(str(e)))
        
        finally:
            self.convert_button.config(state=tk.NORMAL)
            self.select_button.config(state=tk.NORMAL)

if __name__ == "__main__":
    root = tk.Tk()
    app = WordToPdfConverterAlt(root)
    root.mainloop() 